package com.smh.controller;

import com.smh.common.CommonResult;
import com.smh.entity.User;
import com.smh.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin//跨域问题
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/queryAll", method = RequestMethod.POST)
    public CommonResult<ArrayList<User>> queryAll(Integer page, Integer size) {
        return userService.queryAllByPage(page, size);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public CommonResult<User> add(@RequestBody User user) {
        return userService.add(user);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public CommonResult<User> edit(@RequestBody User user) {
        return userService.edit(user);
    }

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    public CommonResult<ArrayList<User>> search(String userName, String realName, Integer page, Integer size) {
        return userService.listByPage(userName,realName,page,size);
    }

    @RequestMapping(value = "/get",method = RequestMethod.POST)
    public CommonResult<User> getUserById(Integer id) {
        CommonResult<User> rs = new CommonResult<>();
        try{
            User user = userService.getUserById(id);
            rs.setCode(0);
            rs.setMsg("获取用户成功");
            rs.setData(user);
            return rs;
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg(e.getMessage());
            return rs;
        }
    }

    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public CommonResult<User> delelete(Integer id) {
        return userService.del(id);
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public CommonResult<String> login(@RequestBody User user) {
        log.info("${}", user);
        return userService.queryByUsernameAndPwd(user);
    }
}
